<?php

namespace app\admin\controller\business;

use app\common\controller\Backend;

use think\Db;

/**
 * 客户管理
 *
 * @icon fa fa-circle-o
 */
class Privatsea extends Backend
{

    //修改是否开启关联查询属性
    protected $relationSearch = true;

    //设置数据控制的关联字段
    protected $dataLimitField = 'adminid';

    //设置看到数据的权限
    protected $dataLimit = 'personal';

    /**
     * Privatsea模型对象
     * @var \app\admin\model\business\Privatsea
     */
    protected $model = null;
    protected $ReceiveModel = null;
    protected $SourceModel = null;
    protected $RegionModel = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = model('Business.Business');

        $this->ReceiveModel = model('Business.Receive');
        $this->SourceModel = model('Business.Source');
        $this->RegionModel = model('Region');
    }

    public function index()
    {
        $this->request->filter(['strip_tags', 'trim']);

        if ($this->request->isAjax()) {
            //Backend 后台基类控制器中提供的一个获取查询条件的参数方法
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $AuthWhere = ['adminid' => ['exp', Db::raw('is not null')]];

            //查询出总条数 和 每页的数据量
            $total = $this->model
                ->with(['source', 'admin', 'provinces', 'citys', 'districts'])
                ->where($where)
                ->where($AuthWhere)
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->count();  //查询总数

            $list = $this->model
                ->with(['source', 'admin', 'provinces', 'citys', 'districts'])
                ->where($where)
                ->where($AuthWhere)
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();  //查询数据

            //返回的数据 下方的这两个参数名字是固定，这个是前台插件(boostrap-table这个插件的固定的)
            $result = ['total' => $total, 'rows' => $list];

            //返回json类型
            return json($result);
        }

        return $this->view->fetch();
    }

    // 添加
    public function add()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post('row/a');

            // 密码加密
            $salt = randstr();
            $password = md5($params['mobile'] . $salt);

            //组装数据
            $data = [
                'nickname' => $params['nickname'],
                'mobile' => $params['mobile'],
                'gender' => $params['gender'],
                'sourceid' => $params['sourceid'],
                'email' => $params['email'],
                'deal' => $params['deal'],
                'adminid' => $this->auth->id,
                'password' => $password,
                'salt' => $salt,
                'auth' => $params['auth'],
                'money' => $params['money'],
                'province' => $params['province'],
                'city' => $params['city'],
                'district' => $params['district'],
                'avatar' => $params['avatar'],
            ];

            // 开启事务
            $this->model->startTrans();
            $this->ReceiveModel->startTrans();

            $BusinessStatus = $this->model->validate("common/Business/Business")->save($data);

            if ($BusinessStatus === FALSE) {
                $this->error($this->model->getError());
                exit;
            }

            // 封装领取数据
            $ReceiveData = [
                'applyid' => $this->auth->id,
                'status' => 'allot',
                'busid' => $this->model->id
            ];

            // 插入领取表
            $ReceiveStatus = $this->ReceiveModel->validate('common/Business/Receive')->save($ReceiveData);

            if ($ReceiveStatus === FALSE) {
                $this->model->rollback();
                $this->error($this->ReceiveModel->getError());
                exit;
            }

            if ($ReceiveStatus === FALSE || $BusinessStatus === FALSE) {
                $this->ReceiveModel->rollback();
                $this->model->rollback();
                $this->error('添加失败');
                exit;
            } else {
                $this->model->commit();
                $this->ReceiveModel->commit();
                $this->success('添加成功');
                exit;
            }
        }


        $this->view->assign("genderList", build_select('row[gender]', model('Business.Business')->getGenderList(), [], ['class' => 'form-control selectpicker']));
        $this->view->assign("dealList", build_select('row[deal]', model('Business.Business')->getDealList(), [], ['class' => 'form-control selectpicker']));
        $this->view->assign('authList', build_select('row[auth]', model('Business.Business')->getAuthList(), [], ['class' => 'form-control selectpicker']));
        $this->view->assign('sourceList', build_select('row[sourceid]', model('Business.Source')->column('id,name'), [], ['class' => 'form-control selectpicker']));

        return $this->view->fetch();
    }

    // 编辑
    public function edit($ids = null)
    {
        $row = $this->model->find($ids);

        if (!$row) 
        {
            $this->error(__('No Results were found'));
            exit;
        }

        if ($this->request->isPost()) 
        {
            $params = $this->request->post('row/a');

            //组装数据
            $data = [
                'id' => $ids,
                'nickname' => $params['nickname'],
                'mobile' => $params['mobile'],
                'gender' => $params['gender'],
                'sourceid' => $params['sourceid'],
                'email' => $params['email'],
                'deal' => $params['deal'],
                'adminid' => $this->auth->id,
                'auth' => $params['auth'],
                'money' => $params['money'],
                'province' => $params['province'],
                'city' => $params['city'],
                'district' => $params['district'],
                'avatar' => $params['avatar'],
            ];

            //判断是否有修改密码
            $password = empty($params['password']) ? '' : trim($params['password']);

            if(!empty($password))
            {
                // 密码加密
                $salt = randstr();
                $data['password'] = md5($password . $salt);
                $data['salt'] = $salt;
            }

            $result = $this->model->validate("common/Business/Business")->isUpdate(true)->save($data);

            if ($result === FALSE) 
            {
                $this->error($this->model->getError());
                exit;
            }else
            {
                //判断是否有上传新图片 
                if($data['avatar'] != $row['avatar'])
                {
                    //不相等就说明有换图片了，就删除掉旧图片
                    @is_file(".".$row['avatar']) && @unlink(".".$row['avatar']);
                }

                $this->success();
                exit;
            }
        }
        
        $this->view->assign('row', $row);
        $this->view->assign('dealList', build_select('row[deal]', model('Business.Business')->getDealList(), $row['deal'], ['class' => 'form-control selectpicker']));
        $this->view->assign('genderList', build_select('row[gender]', model('Business.Business')->getGenderList(), $row['gender'], ['class' => 'form-control selectpicker']));
        $this->view->assign('authList', build_select('row[auth]', model('Business.Business')->getAuthList(), $row['auth'], ['class' => 'form-control selectpicker']));
        $this->view->assign('sourceList', build_select('row[sourceid]', model('Business.Source')->column('id,name'), $row['sourceid'], ['class' => 'form-control selectpicker']));

        return $this->view->fetch();
    }
}
